import {DatePicker, Form, Input, Modal, Select} from 'antd';
import React, {useEffect, useState} from "react";
import {allUser, create} from "@/services";
import {paramType} from "@/utils";
import {getLocalStorage} from "@/utils/localtion";


interface IPubProps {
    open: boolean;
    setOpen: (open: boolean) => void;


}

const {RangePicker} = DatePicker;
const {TextArea} = Input;



const rangeConfig = {
    rules: [{type: 'string' as const, required: true, message: '请选择休假时间'}],
};

const Publish: React.FC<IPubProps> = (props: IPubProps) => {

    const {open, setOpen} = props;
    // 初始化参数

    // TODO 后期这些数据都是由后端传回来的JSON数据直接生成
    const [confirmLoading, setConfirmLoading] = useState(false);
    // 模态对话框标题
    const [modalTitle, setModalTitle] = useState('新建请假流程');
    // 已选择的审核人
    const [approver1, setApprover1] = useState<any[]>([])
    // 第二审核人
    const [approver2, setApprover2] = useState<any[]>([])
    // 第三审核人
    const [approver3, setApprover3] = useState<any[]>([])
    // 所有候选人
    const [users, setUser] = useState<any[]>([])


    // 模态对话框中如何提交表单
    const [form] = Form.useForm()

    // 初始化候选人
    useEffect(() => {
        initData().then()
    }, [])
    // 已选择候选人将不再参与二次审核, 自己也不参与审核
    useEffect(() => {
        setUser(users.filter(o => !approver1.includes(`${o.id}@${o.username}`))
            .filter(o => !approver2.includes(`${o.id}@${o.username}`))
            .filter(o=>!approver3.includes(`${o.id}@${o.username}`))
        )

    }, [approver1, approver2, approver3])
    // 初始化数据
    const initData = async () => {
        const data = await allUser();
        // 不要用 === 来代替,string没有equal方法, == 表示值是否相等, 而 === 表示是否为同一个对象
        if (paramType(data) == "array") {
            // TODO 类型需要进一步确认, 上面判断其实已经返回一个数组了
            // @ts-ignore
            setUser(data)
        }
    }

    const getUserId = (str:string) => str.split("@")[0]
    const getUserName = (str:string) => str.split("@")[1]


    const handleOk = async () => {
        setModalTitle('正在提交');
        // setConfirmLoading(true);
        const formVal = await form.validateFields()
        const userInfo = await JSON.parse(getLocalStorage("userInfo"));
        const {id, username} = userInfo
        const args = {
            name: "请假申请流程",
            status: 0,
            formData: formVal.formData,
            createBy: id||"",
            creator: username,
            approvalData:[
                {status: 0, userId: approver1.map(v=>getUserId(v)), username: approver1.map(v=>getUserName(v))},
                {status: 0, userId: approver2.map(v=>getUserId(v)), username: approver2.map(v=>getUserName(v))},
                {status: 0, userId: approver3.map(v=>getUserId(v)), username: approver3.map(v=>getUserName(v))}
            ]
        }

        create(args).then(() => {
            setOpen(false);
            setConfirmLoading(false);
        })
    };

    const handleCancel = () => {
        setOpen(false);
    };


    return (
        <div>

            <Modal
                title={modalTitle}
                open={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
            >
                {/*    在此处添加表单      */}
                <Form
                    // labelCol={{span: 6}}
                    // wrapperCol={{span: 16}}
                    layout="horizontal"
                    // initialValues={{name: "vacation"}}
                    // onValuesChange={onFormLayoutChange}
                    form={form}
                    style={{maxWidth: 550}}
                >

                    <Form.Item  name="formData">
                        <Form.Item
                            name={["formData", "vacation"]}
                            label="请假类型"
                            rules={[{required: true, message: "请选择休假类型"}]}
                        >
                            <Select >
                                <Select.Option value="事假">事假</Select.Option>
                                <Select.Option value="病假">病假</Select.Option>
                                <Select.Option value="调休">调休</Select.Option>
                                <Select.Option value="年假">年假</Select.Option>

                            </Select>
                        </Form.Item>
                        <Form.Item
                            name={["formData", "rangeTime" ]}

                            label="请假时间" {...rangeConfig}
                                   rules={[{required: true, message: '请选择请假时间'}]}
                        >
                            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
                        </Form.Item>

                        <Form.Item label="请假事由"
                                   name={["formData","reason"]}
                                   rules={[{required: true, message: '请说明请假事由'}]}
                        >
                            <TextArea rows={4}/>
                        </Form.Item>
                    </Form.Item>


                        <Form.Item
                            name={["approvalData","approver1"]} label="审批人1" rules={[{required: true}]}>
                            <Select
                                mode="multiple"

                                placeholder="请选择审批人"
                                value={approver1}
                                onChange={setApprover1}
                                options={users.map((item) => ({
                                    // 这里因为any的原因出现字段不明确的隐患
                                    value: `${item.id}@${item.username}`,
                                    label: item.username,
                                }))}
                            />
                        </Form.Item>
                        <Form.Item  name={["approvalData","approver2"]} label="审批人2" rules={[{required: true}]}>
                            <Select
                                mode="multiple"
                                placeholder="请选择审批人"
                                value={approver2}
                                onChange={setApprover2}
                                options={users.map((item) => ({
                                    // 这里因为any的原因出现字段不明确的隐患
                                    value: `${item.id}@${item.username}`,
                                    label: item.username,
                                }))}
                            />
                        </Form.Item>
                        <Form.Item  name={["approvalData","approver3"]} label="审批人3" rules={[{required: true}]}>
                            <Select
                                mode="multiple"
                                placeholder="请选择审批人"
                                value={approver3}
                                onChange={setApprover3}
                                options={users.map((item) => ({
                                    // 这里因为any的原因出现字段不明确的隐患
                                    value: `${item.id}@${item.username}`,
                                    label: item.username,
                                }))}
                            />
                        </Form.Item>



                </Form>

            </Modal>
        </div>
    );
};

export default Publish;
